//
//  Regex.m
//  parser
//
//  Created by Daniel Braun on 04/05/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "DBRegex.h"




@implementation DBRegex

- (int) matchStartOfString:(NSString *)s
{	
	NSRange r=[self matchRangeInString:s];
	if (r.length<=0) return 0;
	if (r.location>0) return 0;
	return r.length;
}

- (BOOL) matchInString:(NSString *)s
{
	NSRange r=[self matchRangeInString:s];
	return (r.length>0);
}

- (NSRange) matchRangeInString:(NSString *)s
{
	return  [self matchRangeInString:(NSString *)s offset:0];
}

- (NSRange) matchRangeInString:(NSString *)s offset:(int)l
{
	int rc;
	regmatch_t m;
	if (l>=[s length]) return  NSMakeRange(0,0);
	rc=regexec(&regex, [s UTF8String]+l, 1, &m, 0);
	if (rc) return NSMakeRange(0,0);
	NSRange r;
	r.location=m.rm_so + l;
	r.length=m.rm_eo-m.rm_so;
	return r;
}

- (void) dealloc {
	if (hasRegex) regfree(&regex);
	[pattern release];
	[super dealloc];
}
- (void)encodeWithCoder:(NSCoder *)coder
{
	//[super encodeWithCoder:coder];
	if ( [coder allowsKeyedCoding] ) {
		[coder encodeObject:pattern forKey:@"pattern"];
	}
}

- (id) initWithCoder:(NSCoder *) coder
{
	//self=[super initWithCoder:coder];
	//self=[super init];
	if ([coder allowsKeyedCoding]) {
		NSString *p=[coder decodeObjectForKey:@"pattern"];
		if (p) return [self initWithPattern:p];
	}
	return nil;
}

- (NSString *) description
{
	return [NSString stringWithFormat:@"regex(%@)", pattern];
}

- (id) initWithPattern:(NSString *)s
{
	self = [super init];
	if (self != nil) {
		int rc;
		rc=regcomp(&regex, [s UTF8String], REG_EXTENDED);
		if (rc) {
			NSLog(@"bad regular expr pattern\n");
			[self release];
			return nil;
		}
		pattern=[s copy];
		hasRegex=YES;
	}
	return self;
}


+ (id) regexWithPattern:(NSString *)s
{
	id sl=[[[[self class]alloc]initWithPattern:s]autorelease];
	return sl;
}


@end
